//
//  CoursesSearchViewController.m
//  classroom
//
//  Created by apple on 12-10-28.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CoursesSearchViewController.h"
#import "CoursesSearchTableViewCell.h"
#import "JSONKit.h"
#import "ASIHTTPRequest.h"
#import "UrlData.h"
#import "Notifications.h"
//#import <SDWebImage/UIImageView+WebCache.h>
#import "UIImageView+WebCache.h"

@interface CoursesSearchViewController (){
    ChooseView *chooseView;
//    UIView *footerView;
}

@end

@implementation CoursesSearchViewController

@synthesize searchCondition;//
@synthesize courseResultArray;
@synthesize resultDic;
@synthesize typeArray;
@synthesize priceArray;
@synthesize areaArray;
@synthesize searchConditionDic;//存放搜索条件的字典

@synthesize waitIndicatorView;//activityIndicatorView
@synthesize loadinglabel;
@synthesize searchtableView;
@synthesize courseInformationViewController = _courseInformationViewController;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title = @"课程搜索";

    //初始化服务器返回的结果字典
    resultDic=[[NSMutableDictionary alloc]init];
    
    //初始化 服务器返回的课程array
    courseResultArray=[[NSMutableArray alloc]init];
    
    //初始化 下拉列表array
    typeArray=[[NSMutableArray alloc]init];
    priceArray=[[NSMutableArray alloc]init];
    areaArray=[[NSMutableArray alloc]init];
    
    searchCondition=-1;
    searchConditionDic=[[NSMutableDictionary alloc]init];
    //***测试下拉列表****
   
    
    //向服务器请求数据
    [self requestData];
    
    //初始化 tableview
    searchtableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 30, 320, 480-20-44-30) style:UITableViewStylePlain];
//    searchtableView.layer.cornerRadius = 6;
//    searchtableView.layer.masksToBounds = YES;
    searchtableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [searchtableView setDelegate:self];
    [searchtableView setDataSource:self];
    searchtableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"CourseSearch_TableViewBG_ImageView"]];
    [self.view addSubview:searchtableView];
    
    [self displayActiveIndicatorView];//显示等待ActiveIndicatorView
  
    chooseView = [[ChooseView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
    [chooseView setButtonEnable:NO];
    [self.view addSubview:chooseView];
    chooseView.delegate = self;
}

- (void)viewDidUnload
{
    [self setSearchtableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    searchtableView 
}

#pragma mark -
#pragma mark 翻页
- (void)nextPageButtonPressed:(UIButton *)sender //下一页按钮被点击
{
//    NSString *urlString=[NSString stringWithFormat:@"%@",ClassRoom_URL];
//    
//    NSURL *url=[NSURL URLWithString:urlString];
//    
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//    
//    [request setDelegate:self];
//    [request startAsynchronous];
}

#pragma mark -
#pragma mark UIActivityIndicatorView

//开始显示 UIActivityIndicatorView
- (void) displayActiveIndicatorView 
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    if (waitIndicatorView == nil) {
        waitIndicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(140, 100, 46, 46)];
        loadinglabel=[[UILabel alloc]initWithFrame:CGRectMake(140, 140, 80, 30)];
        loadinglabel.text=@"loading...";
        loadinglabel.BackgroundColor=[UIColor clearColor];
        [waitIndicatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
        [waitIndicatorView startAnimating];
        
        [self.view addSubview:waitIndicatorView];
        [self.view addSubview:loadinglabel];
    }
    
    [pool release];
}
//结束显示 UIActivityIndicatorView
- (void) dismissActiveIndicatorView
{
    if (waitIndicatorView)
    {
        [waitIndicatorView stopAnimating];
        [waitIndicatorView removeFromSuperview];
        [waitIndicatorView release]; waitIndicatorView = nil;
        [loadinglabel removeFromSuperview];
        [loadinglabel release];
        loadinglabel=nil;
    }
}


#pragma mark -
#pragma mark ASIHTTPRequest
-(void)requestData
{
    NSString *urlString=[self geturlString];//生成url
    
    NSLog(@"urlstring=%@",urlString);
    NSURL *url=[NSURL URLWithString:urlString];
    NSLog(@"url=%@",url);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    [request setDelegate:self];
    [request startAsynchronous];
    
}

//生成url
-(NSString *)geturlString
{
    NSString *urlString=@"";
    if (searchConditionDic.count==0) {
        urlString=[NSString stringWithFormat:@"%@%@",ClassRoom_URL,SearchCourseSummary_URL];     
        
    }else {
        urlString=[NSString stringWithFormat:@"%@%@sum=20&page=%@&price=%@&address=%@&classKind=%@",ClassRoom_URL,SearchCourse_URL,[searchConditionDic objectForKey:@"page"],[searchConditionDic objectForKey:@"price"],[searchConditionDic objectForKey:@"address"],[searchConditionDic objectForKey:@"classKind"]];
    }
   
    NSLog(@"urlString=%@",urlString);
    return urlString;
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSLog(@"requestFinished");
    NSString *responseString = [request responseString];
    NSLog(@"responseString------>>%@",responseString);
    
    resultDic=[[responseString objectFromJSONString] retain];//将所有的结果放到其中,接下来根据key取出相应的数据
    NSLog(@"resultDic--->>>%@",resultDic);
    //if (searchCondition==-1) {
    if (searchConditionDic.count==0) {
        [self setPullDownMenus]; //设置下拉列表
        NSLog(@"searchCondition 为0");
      
    }
    if(searchConditionDic.count==0)
    {
       
        [self setCourseArray];
        [searchtableView reloadData];
     
    }else {
       NSString * coursesum=(NSString *)[resultDic objectForKey:@"courseSum"];
        NSLog(@"courseSum=%@",coursesum);
        if ([coursesum intValue]==0) {
            NSLog(@"222结果为空");
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [al show];
            [al release];

            return;
         
        }else {
          
            NSLog(@"不为空");
            [self setCourseArray];
            [searchtableView reloadData];
        }
    }
    
    [self dismissActiveIndicatorView];//结束显示ActiveIndicatorView
}

- (void)requestFailed:(ASIHTTPRequest *)request

{
    
    NSError *error = [request error];
    NSLog(@"%@",error);
    
}

#pragma mark -
#pragma mark 用返回的值初始化 array等
-(void)setPullDownMenus
{
    //真实request用一下代码，注意是否需要用retain
   
    NSMutableDictionary *pullDownMenusDic=(NSMutableDictionary *)[resultDic objectForKey:@"searchCourseSummary"];
    NSLog(@"resultdic=%@",resultDic);
    NSString *typeArrayStr=(NSString *)[pullDownMenusDic objectForKey:@"type"];
    typeArray=(NSMutableArray *)[typeArrayStr componentsSeparatedByString:@","];
    [typeArray retain];
    
    NSString *priceArrayStr=(NSString *)[pullDownMenusDic objectForKey:@"price"];
    priceArray=(NSMutableArray *)[priceArrayStr componentsSeparatedByString:@","];
    [priceArray retain];
    
    NSString *areaArrayStr=(NSString *)[pullDownMenusDic objectForKey:@"area"];
    areaArray=(NSMutableArray *)[areaArrayStr componentsSeparatedByString:@","];
    [areaArray retain];
    
    chooseView.kindArrary = typeArray;
    chooseView.priceArray = priceArray;
    chooseView.addressArray = areaArray;
    [chooseView setButtonEnable:YES];

}

-(void)setCourseArray// 设置课程列表，array中的值为字典
{   
    if(searchConditionDic.count==0)
    {
        NSMutableDictionary *searchCourseSummaryDic=(NSMutableDictionary *)[resultDic objectForKey:@"searchCourseSummary"];
        courseResultArray=[searchCourseSummaryDic objectForKey:@"course"];
        NSLog(@"courseResultArray=%@",courseResultArray);
    }else {
         NSMutableDictionary *searchCourseSummaryDic=(NSMutableDictionary *)[resultDic objectForKey:@"course"];
        courseResultArray=[searchCourseSummaryDic objectForKey:@"course"];
         NSLog(@"courseResultArray=%@",courseResultArray);
    }
}   
-(void)setConditionDic:(NSString *)value forkey:(NSString *)key
{   //设置搜索条件
       //@"http://192.168.1.9:8080/Classroom/SearchCourse?sum=20&page&price=0&address=chaoyang&classKind=siji"
    //设置全选
    if (searchConditionDic.count==0) {
        [searchConditionDic setObject:@"0" forKey:@"page"];
        [searchConditionDic setObject:@"0" forKey:@"price"];
        [searchConditionDic setObject:@"null" forKey:@"address"];
        [searchConditionDic setObject:@"null" forKey:@"classKind"];
    }
    [searchConditionDic removeObjectForKey:key];
    [searchConditionDic setObject:value forKey:key];
}
    
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(void)popoverViewSelect
{
    [self requestData];
}

- (void)dealloc {
    [searchtableView release];
//    [footerView release];
    
    [super dealloc];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [courseResultArray count];
    //return [nameResult count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 386/7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CoursesSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(cell == nil)
    {
        cell = [[[CoursesSearchTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }

    //设置tablecell的内容
    [cell setCellData:(NSDictionary *)[courseResultArray objectAtIndex:indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [self.courseResultArray count]-1) {
        
        UIView *footerView = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];    
        footerView.backgroundColor = [UIColor clearColor];
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        moreButton.backgroundColor = [UIColor redColor];
        moreButton.frame = CGRectMake(0, 0, 320, 44);
        [moreButton setTitle:@"点击以获取更多" forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(nextPageButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:moreButton];
        
        searchtableView.tableFooterView = footerView;
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    CourseInformationViewController *courseInformationViewController = [[[CourseInformationViewController alloc] init] autorelease];
//    NSLog(@" = %@",[(NSDictionary *)[courseResultArray objectAtIndex:indexPath.row] class]);
////    courseInformationViewController.courseInformationDictionary = (NSDictionary *)[courseResultArray objectAtIndex:indexPath.row];
//    [self.navigationController pushViewController:courseInformationViewController animated:YES];
    
    
    if (!self.courseInformationViewController)
    {
        self.courseInformationViewController = [[CourseInformationViewController alloc] init];
    }
//    NSString *largeImageURL = [[[[courseResultArray objectAtIndex:indexPath.row] objectForKey:@"information"]objectForKey:@"logourl"] stringByReplacingOccurrencesOfString:@"small" withString:@"source"];
    NSString *largeImageURL = [NSString stringWithFormat:@"http://www.sinaimg.cn/dy/slidenews/3_img/2012_52/37294_245310_464968.jpg"];
    self.courseInformationViewController.imageURL = [NSURL URLWithString:largeImageURL];
    [self.navigationController pushViewController:self.courseInformationViewController animated:YES];
    [self.courseInformationViewController SetSomeChanges:(NSDictionary *)[[courseResultArray objectAtIndex:indexPath.row] objectForKey:@"information"]buttonEnable:NO];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark-
#pragma mark ChooseViewDelegate
- (void)didSelecteIndex:(NSIndexPath *) indexPath title:(NSString *) title
{
    NSLog(@"%@",title);
}

@end

